<template>
  <el-dialog v-model="model" @close="closedDialog">
    <el-form ref="userFormRef" :model="form" label-width="120px" :rules="rules">
      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('sysUser.directory')" prop="directoryId">
            <el-select
              v-model="form.directoryId"
              :placeholder="$t('sysUser.directoryRequired')"
              clearable
              filterable
              allow-create
              style="width: 100%"
            >
              <el-option
                v-for="item in directoryList"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('sysUser.username')" prop="loginName">
            <el-input
              v-model="form.loginName"
              clearable
              :placeholder="$t('sysUser.usernameRequired')"
              maxlength="30"
              show-word-limit
              @change="handleExist($event, $t('sysUser.username'))"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('sysUser.nickname')" prop="nickName">
            <el-input
              v-model="form.nickName"
              clearable
              maxlength="30"
              show-word-limit
              :placeholder="$t('sysUser.nicknameRequired')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            v-if="!(form as UserUpdateReq).userId"
            :label="$t('sysUser.password')"
            prop="pwd"
          >
            <el-input
              v-model="(form as UserCreateReq).pwd"
              type="password"
              show-password
              clearable
              :placeholder="$t('sysUser.passwordRequired')"
              @change="handlePwdChange"
            >
              <template #append>
                <el-button @click="pwdRandom">
                  {{ $t("sysUser.randomPwd") }}
                </el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('sysUser.fullName')" prop="realName">
            <el-input
              v-model="form.realName"
              clearable
              maxlength="30"
              show-word-limit
              :placeholder="$t('sysUser.fullNameRequired')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('sysUser.gender')" prop="gender">
            <jmash-enum-select
              v-model="form.gender"
              clearable
              :placeholder="$t('sysUser.genderRequired')"
              enum-type="jmash.protobuf.Gender"
              class="w-full"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('sysUser.phoneNumber')" prop="mobilePhone">
            <el-input
              v-model="form.mobilePhone"
              :placeholder="$t('sysUser.phoneNumberRequired')"
              clearable
              @change="handleExist($event, $t('sysUser.phoneNumber'))"
            >
              <template #append>
                <el-checkbox
                  v-model="form.phoneApproved"
                  :disabled="!(form as UserUpdateReq).userId"
                  label="通过手机号验证"
                />
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('sysUser.email')" prop="email">
            <el-input
              v-model="form.email"
              :placeholder="$t('sysUser.emailRequired')"
              clearable
              maxlength="30"
              show-word-limit
              @change="handleExist($event, $t('sysUser.email'))"
            >
              <template #append>
                <el-checkbox
                  v-model="form.emailApproved"
                  :disabled="!(form as UserUpdateReq).userId"
                  label="通过邮件验证"
                />
              </template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('sysUser.birthday')" prop="birthDate">
            <el-date-picker
              v-model="form.birthDate"
              type="date"
              :placeholder="$t('sysUser.birthdayRequired')"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('sysUser.role')" prop="roleIds">
            <el-tree-select
              v-model="form.roleIds"
              :data="rolesArray"
              :render-after-expand="false"
              show-checkbox
              :check-strictly="true"
              multiple
              clearable
              style="width: 100%"
              :placeholder="$t('sysUser.roleRequired')"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <div class="positon_name">
        <el-row
          v-for="(item, index) in form.userJobs"
          :key="index"
          style="width: 100%"
        >
          <el-col :span="12">
            <el-form-item
              :label="$t('sysUser.department')"
              :prop="`userJobs.${index}.deptId`"
            >
              <el-tree-select
                v-model="form.userJobs![index].deptId"
                :data="deptsArray"
                :render-after-expand="false"
                filterable
                clearable
                check-strictly
                :placeholder="$t('sysUser.departmentRequired')"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item
              :label="$t('sysUser.position')"
              :prop="`userJobs.${index}.jobId`"
            >
              <el-tree-select
                v-model="form.userJobs![index].jobId"
                :data="jobsArray"
                :render-after-expand="false"
                filterable
                clearable
                check-strictly
                :placeholder="$t('sysUser.positionRequired')"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col v-if="index === 0" :span="1" class="position-center">
            <el-icon size="16" @click="domainsAdd">
              <CirclePlus />
            </el-icon>
          </el-col>
          <el-col v-if="index !== 0" :span="1" class="position-center">
            <el-icon size="16" @click="domainsRemove(index)">
              <Remove />
            </el-icon>
          </el-col>
        </el-row>
      </div>
      <el-row v-if="useUserStore().user.tenant.includes('@') && !update">
        <el-col :span="12">
          <el-form-item :label="$t('sysUser.platUser')" prop="createPlatformUser">
            <el-checkbox v-model="form.createPlatformUser" label="是" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <jmash-table
      v-if="(form as UserUpdateReq).userId"
      :list-loading="listLoading"
      :data="tableData"
      :table-label="tableLabel"
      :is-selection="false"
    >
      <template #openType="scope">
        <span>{{
          Dict.opensTypeEnum.getEnumValue(scope.data.row.openType)
        }}</span>
      </template>
      <template #operation="scope">
        <el-button
          v-hasPerm="['rbac:opens:delete']"
          link
          size="small"
          type="primary"
          :icon="Key"
          @click="unBindOpensEvent(scope.data.row)"
        >
          {{ $t("common.unbind") }}
        </el-button>
      </template>
    </jmash-table>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closedDialog">{{ $t("common.cancel") }}</el-button>
        <el-button type="primary" @click="submitForm">
          {{ $t("common.confirm") }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { type Ref, ref, reactive, type PropType } from "vue";
import { useI18n } from "vue-i18n";
const { t } = useI18n();
import { type FormInstance, type FormRules, ElMessage } from "element-plus";
import { useUserStore, type TableColumn, vueMetaEnv } from "jmash-core";
import { Dict } from "@/api/system/index";

import { generateRandomKey } from "@/utils/common";
import { Key } from "@element-plus/icons-vue";
import type {
  UserFormReq,
  UserKey,
  UserUpdateReq,
  UserCreateReq,
  UserOpenModel,
} from "@/api/system/user/types";
import { userApi } from "@/api/system/user/index";
import { roleApi } from "@/api/system/role/index";
import { deptApi } from "@/api/system/dept/index";
import { jobApi } from "@/api/system/job/index";
const userFormRef = ref<FormInstance>();
const model = defineModel<boolean>();
const rolesArray = ref();
const deptsArray = ref();
const jobsArray = ref();
const directoryList = ref();
let form: UserFormReq = reactive({
  requestId: Math.random() * 10 + "",
  updateMask:
    "directoryId,loginName,nickName,realName,gender,birthDate,mobilePhone,email,emailApproved,phoneApproved,roleIds,userJobs",
  status: "enabled",
  userJobs: [
    {
      deptId: "",
      jobId: "",
    },
  ],
  createPlatformUser: useUserStore().user.tenant.includes('@') ? true : false,
});
const rules = reactive<FormRules<UserFormReq>>({
  directoryId: [
    {
      required: true,
      message: t("sysUser.directoryRequired"),
      trigger: "change",
    },
  ],
  loginName: [
    { required: true, message: t("sysUser.usernameRequired"), trigger: "blur" },
  ],
  nickName: [
    { required: true, message: t("sysUser.nicknameRequired"), trigger: "blur" },
  ],
  mobilePhone: [
    {
      pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
      message: t("sysUser.correctPhone"),
      trigger: "blur",
    },
  ],
  email: [
    {
      pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
      message: t("sysUser.correctEmail"),
      trigger: "blur",
    },
  ],
  roleIds: [
    { required: true, message: t("sysUser.roleRequired"), trigger: "blur" },
  ],
});
const props = defineProps({
  entityKey: {
    type: Object as PropType<UserKey>,
    default: () => {},
  },
});
const emits = defineEmits(["refresh"]);
// table
const listLoading = ref(false);
const tableData = ref<UserOpenModel[]>([]);
const tableLabel: Ref<TableColumn[]> = ref([
  {
    label: "sysUser.type",
    prop: "openType",
    isColumn: true,
    slotName: "openType",
    columnType: "slot",
    width: "100",
  },
  {
    label: "sysUser.AppId",
    prop: "appId",
    isColumn: true,
    width: "180",
  },
  {
    label: "sysUser.OpenId",
    prop: "openId",
    isColumn: true,
  },
  {
    label: "sysUser.UnionId",
    prop: "unionId",
    isColumn: true,
  },
  {
    label: "common.operate",
    slotName: "operation",
    columnType: "slot",
    fixed: "right",
    width: "80",
    isColumn: true,
  },
]);

function domainsAdd() {
  if (form.userJobs && form.userJobs.length < 5)
    form.userJobs?.push({
      deptId: "",
      jobId: "",
    });
}

function domainsRemove(index: number) {
  form.userJobs?.splice(index, 1);
}

// 获取随机密码
function pwdRandom() {
  (form as UserCreateReq).pwd = generateRandomKey();
  (form as UserCreateReq).repeatPwd = (form as UserCreateReq).pwd;
}

function handlePwdChange(value: string) {
  (form as UserCreateReq).repeatPwd = value;
}

const keys = Object.keys(props.entityKey);

const update = ref(keys.length >= 1);

if (update.value) {
  userApi.findById(props.entityKey).then(({ data }) => {
    Object.assign(form, data);
    if (form.userJobs?.length === 0) {
      form.userJobs = [
        {
          deptId: "",
          jobId: "",
        },
      ];
    }
    if (form.gender === "unknown") {
      form.gender = "";
    }
    getList(data.userId);
  });
 
}

// 提交表单校验
const submitForm = async () => {
  await userFormRef.value?.validate((valid) => {
    if (valid) {
      // 创建平台用户
      form.platformTenant = form.createPlatformUser ? vueMetaEnv.APP_TENANT : "";
      form.approved = true;
      if (update.value) {
        userApi.update(form as UserUpdateReq).then((response) => {
          if (response.status === 200) {
            ElMessage({
              message: t("common.submitSuccess"),
              type: "success",
            });
            if (model.value) {
              model.value = false;
            }
            emits("refresh", response.status === 200);
          }
        });
      } else {
        userApi.create(form).then((response) => {
          if (response.status === 200) {
            ElMessage({
              message: t("common.submitSuccess"),
              type: "success",
            });
            if (model.value) {
              model.value = false;
            }
            emits("refresh", response.status === 200);
          }
        });
      }
    }
  });
};

// 关闭弹框
function closedDialog() {
  if (model.value) {
    model.value = false;
  }
}

// 校验用户名/手机号/邮箱是否存在
function handleExist(val: string, info: string) {
  userApi
    .existUser(
      (form as UserUpdateReq).userId
        ? ((form as UserUpdateReq).userId as string)
        : "",
      val,
    )
    .then(({ data }) => {
      if (data === true) {
        ElMessage({
          message: info + t("sysUser.exists"),
          type: "warning",
        });
      }
    });
}

// 解绑
function unBindOpensEvent(row: any) {
  ElMessageBox.confirm(t("common.confirmUnbind"), t("common.unbind"), {
    cancelButtonText: t("common.cancel"),
    confirmButtonText: t("common.confirm"),
    type: "warning",
  })
    .then(() => {
      const data = {
        tenant: useUserStore().user.tenant,
        appId: row.appId,
        userId: row.userId,
        openId: row.openId,
      };
      userApi.unBindOpens(data).then((response) => {
        if (response.status === 200) {
          ElMessage({
            message: t("common.successUnbind"),
            type: "success",
          });
          getList(data.userId);
        }
      });
    })
    .catch(() => {});
}

function queryUserData() {
  roleApi.treelistRole().then(({ data }) => {
    rolesArray.value = data.results;
  });
  deptApi.treelistDept().then(({ data }) => {
    deptsArray.value = data.results;
  });
  jobApi.treelistJob().then(({ data }) => {
    jobsArray.value = data.results;
  });
  userApi.getDirectoryApi().then(({ data }) => {
    directoryList.value = data.directoryId;
  });
}

function getList(userId:string) {
  listLoading.value = true;
  console.log(userId);
  userApi
    .openList({ userId: userId })
    .then(({ data }) => {
      tableData.value = data.results;
      listLoading.value = false;
    });
}
queryUserData();
</script>
<style scoped lang="scss">
.position-center {
  position: absolute;
  right: 0;
  top: 30%;
  transform: translate(0, -30%);
}

.plus-position {
  position: absolute;
  right: 0;
  top: 0;
  margin-top: 8px;
}
.w-full {
  width: 100% !important;
}
</style>
